package data

import (
	"strconv"
	"time"
)

// (D:YYYYMMDDHHmmSSOHH'mm')
type Date struct {
	value time.Time
}

func (this *Date) ParseFrom(from *AsciiString) error {
	value := from.GetValue()
	startIndex := 0
	if value[0] == 'D' && value[1] == ':' {
		startIndex = 2
	}
	year, monthStart := mustParseInt(value, startIndex, 4, 1970)
	month, dayStart := mustParseInt(value, monthStart, 2, 1)
	day, hourStart := mustParseInt(value, dayStart, 2, 1)
	hour, minuteStart := mustParseInt(value, hourStart, 2, 0)
	minute, secondStart := mustParseInt(value, minuteStart, 2, 0)
	second, ofUtStart := mustParseInt(value, secondStart, 2, 0)
	ofUTC := value[ofUtStart]
	ofHour, ofMinuteStart := mustParseInt(value, ofUtStart+1, 2, 0)
	ofMinute, _ := mustParseInt(value, ofMinuteStart, 2, 0)
	if ofUTC == '-' {
		ofHour = -ofHour
		ofMinute = -ofMinute
	} else if ofUTC == 'Z' {
		ofHour = 0
		ofMinute = 0
	}
	loc := time.FixedZone("", ofHour*60*60+ofMinute*60)
	this.value = time.Date(year, time.Month(month), day, hour, minute, second, 0, loc)
	return nil
}
func mustParseInt(bs []byte, startIndex, offset int, dv int) (int, int) {
	endIndex := startIndex + offset
	if startIndex > len(bs) {
		return dv, endIndex
	}
	if endIndex > len(bs) {
		return dv, endIndex
	}
	rst, err := strconv.ParseInt(string(bs[startIndex:endIndex]), 10, 64)
	if err != nil {
		panic(err)
	}
	return int(rst), endIndex
}
